<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function uploadUserAvatar(Request $request)
    {
        $file = $request->file('file');
        if (! $file) {
            throw new ApiException('需要上传文件', 1);
        }
//        if ($file->getSize() > 522000) {
//            throw new ApiException('文件体积过大, 应小于 500kb, 当前大小为 ' . ceil($file->getSize() / 1024) . 'kb', 1);
//        }
        $path = $file->store('static_files/userAvatar/' . date('Y-m-d', time()));
        return renderSuccessJson([
            'url' => config('app.url') . Storage::url($path),
            'path' => Storage::url($path),
        ]);
    }

    public function uploadImages(Request $request)
    {
        $file = $request->file('file');
        if (! $file) {
            throw new ApiException('需要上传文件', 1);
        }
//        if ($file->getSize() > 522000) {
//            throw new ApiException('文件体积过大, 应小于 500kb, 当前大小为 ' . ceil($file->getSize() / 1024) . 'kb', 1);
//        }
        $path = $file->store('static_files/images/' . date('Y-m-d', time()));
        return renderSuccessJson([
            'url' => config('app.url') . Storage::url($path),
            'path' => Storage::url($path),
        ]);
    }

    //  上传一些
    public function uploadOffice(Request $request)
    {
        $file = $request->file('file');
        if (! $file) {
            throw new ApiException('需要上传文件', 1);
        }
        $path = $file->store('static_files/office/' . date('Y-m-d', time()));
        return renderSuccessJson([
            'url' => config('app.url') . Storage::url($path),
            'path' => Storage::url($path),
            'extra_name' => $file->getClientOriginalName(),
        ]);
    }

    public function specialUploadLayEdit(Request $request)
    {
        $file = $request->file('file');
        if (! $file) {
            throw new ApiException('需要上传文件', 1);
        }
//        if ($file->getSize() > 522000) {
//            throw new ApiException('文件体积过大, 应小于 500kb, 当前大小为 ' . ceil($file->getSize() / 1024) . 'kb', 1);
//        }
        $path = $file->store('static_files/images/' . date('Y-m-d', time()));

        return [
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'src' => config('app.url') . Storage::url($path),
                'title' => $request->input('title') ?? '',
            ],
        ];
    }

    public function download(Request $request)
    {
        $path = $request->input('path');

        // 不知道为什么要去掉 /storage
        $path = str_replace('/storage', '', $path);
        return Storage::download($path);
    }
}
